package com.lcq.gulimall.order.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class MyRabbitConfig {
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Bean
    public MessageConverter JsonMessageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    @PostConstruct
    public void initRabbitTemplate(){
        rabbitTemplate.setConfirmCallback((correlationData, b, s) -> System.out.println("Confirm ack:"+b));
        rabbitTemplate.setReturnCallback((message, replyCode, replyText,exchange, routingKey)->{
            System.out.println("ReturnCallback "+message+"replyCode:"+replyCode+"replyText:"+replyText);
        });
    }

    @Bean
    public Queue orderDelayQueue(){
        Map arguments = new HashMap();
        arguments.put("x-message-ttl",60000);
        arguments.put("x-dead-letter-exchange","order-event-exchange");
        arguments.put("x-dead-letter-routing-key","order.release.queue");
        return new Queue("order-delay-queue",false,false,false, arguments);
    }

    @Bean
    public Queue orderReleaseQueue(){
        return new Queue("order-release-queue",false,false,false, null);
    }

    @Bean
    public Exchange orderEventExchange(){
        return new TopicExchange("order-event-exchange",false,false,null);
    }

    @Bean
    public Binding eventDelayBinding(){
        return new Binding("order-delay-queue",
                Binding.DestinationType.QUEUE,
                "order-event-exchange",
                "order.delay.queue",
                null);
    }

    @Bean
    public Binding eventReleaseBinding(){
        return new Binding("order-release-queue",
                Binding.DestinationType.QUEUE,
                "order-event-exchange",
                "order.release.queue",
                null);
    }

    @Bean
    public Queue orderSecKillQueue(){
        return new Queue("order-seckill-queue",false,false,false, null);
    }

    @Bean
    public Binding eventSecKillBinding(){
        return new Binding("order-seckill-queue",
                Binding.DestinationType.QUEUE,
                "order-event-exchange",
                "order.seckill.queue",
                null);
    }
}
